use bindgen::EnumVariation;
use std::char;
use std::env;
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};

macro_rules! p {
    ($($tokens: tt)*) => {
        println!("cargo:warning={}", format!($($tokens)*))
    }
}

pub fn main() {
    // 根据操作系统设置不同的库路径
    let libs_path = match std::env::consts::OS {
        "macos" => PathBuf::from("./libs/macos"),
        "windows" => PathBuf::from("./libs/windows"),
        "linux" => PathBuf::from("./libs/linux"),
        _ => panic!("Unsupported operating system: {}", std::env::consts::OS),
    };

    println!("cargo:rustc-link-search=native={}", libs_path.display());

    // 根据操作系统设置不同的链接标志
    match std::env::consts::OS {
        "macos" => println!("cargo:rustc-flags=-l dylib=c++"),
        "windows" => println!("cargo:rustc-link-lib=dylib=user32"),
        "linux" => println!("cargo:rustc-flags=-l dylib=stdc++"),
        _ => {}
    }

    let mut objs = ["manifold"];
    for obj in objs {
        println!(
            "cargo:rustc-link-search=native={}/{}/",
            libs_path.display(),
            obj
        );
        println!("cargo:rustc-link-lib=static={}", obj);
    }
    println!("cargo:rustc-link-lib=static=manifoldc");
    println!("cargo:rustc-link-lib=static=manifold");
    println!("cargo:rustc-link-lib=static=Clipper2");
    let bindings = bindgen::Builder::default()
        // The input header we would like to generate
        // bindings for.
        .header("c/include/manifoldc.h")
        .clang_arg("-Ic/include")
        .parse_callbacks(Box::new(bindgen::CargoCallbacks))
        // Finish the builder and generate the bindings.
        .generate()
        // Unwrap the Result and panic on failure.
        .expect("Unable to generate bindings");

    // Write the bindings to the $OUT_DIR/bindings.rs file.
    // let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
    let out_path: PathBuf = "src/generated".into();
    bindings
        .write_to_file(out_path.join("bindings.rs"))
        .expect("Couldn't write bindings!");
}
